package cn.iocoder.yudao.module.member.service.order;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.member.controller.admin.siteconfig.vo.SiteConfigurationVo;
import cn.iocoder.yudao.module.member.controller.admin.siteconfig.vo.SysLinkVo;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.AppAuthLoginRespVO;
import cn.iocoder.yudao.module.member.controller.app.order.vo.AppMemberCertificateOrderVo;
import cn.iocoder.yudao.module.member.controller.app.order.vo.RequestSysVo;
import cn.iocoder.yudao.module.member.dal.dataobject.order.MemberCertificateOrderDo;
import cn.iocoder.yudao.module.member.dal.redis.no.OrderNoRedisDAO;
import cn.iocoder.yudao.module.member.enums.SysFlagEnum;
import cn.iocoder.yudao.module.member.service.siteconfiguration.SiteConfigurationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.MAIN_URL_ERROR;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.MAIN_URL_EXCEPTION;

@Slf4j
@Service
public class XingHangStrategy implements SysLinkStrategy{

    private final String SITE_CONFIG_CACHE_TOKEN = "SITE:CONFIG:CACHE:TOKEN";
    //B系统调用A系统的接口
    private final String B_To_A = "/app-api/member/certificate/createOrder";

    private final String GETBYID = "/app-api/member/certificate/getById";

    private final String Login_TO_A = "/app-api/member/auth/loginByToken";

    private final String SITE_CONFIG_CACHE_MAIN_URL = "SITE:CONFIG:CACHE:MAIN:URL";
    @Resource
    private OrderNoRedisDAO orderNoRedisDAO;
    @Resource
    private SiteConfigurationService siteConfigurationService;
    @Override
    public MemberCertificateOrderDo createOrder(AppMemberCertificateOrderVo appOrderVo) {
        String token = orderNoRedisDAO.getValue(SITE_CONFIG_CACHE_TOKEN);
        String mainUrl = orderNoRedisDAO.getValue(SITE_CONFIG_CACHE_MAIN_URL);
        try {
            //调用登录接口
            HttpResponse executeLogin = HttpUtil.createGet(mainUrl + Login_TO_A+"?token="+token).execute();
            if (!executeLogin.isOk()){
                throw exception(MAIN_URL_ERROR);
            }
            String s = JSONUtil.toJsonStr(executeLogin.body());
            RequestSysVo<AppAuthLoginRespVO> requestSysVo = JSONUtil.toBean(s, RequestSysVo.class);
            log.info("系统登录返回日志信息{}",s);
            if (0 == requestSysVo.getCode()){
                AppAuthLoginRespVO appAuthLoginRespVO = JSONUtil.toBean( JSONUtil.toJsonStr( requestSysVo.getData()), AppAuthLoginRespVO.class);
                HttpResponse execute = HttpUtil.createPost(mainUrl + B_To_A).header("Authorization","Bearer "+appAuthLoginRespVO.getAccessToken()).body(JSONUtil.toJsonStr(appOrderVo)).execute();
                if (!execute.isOk()){
                    throw exception(MAIN_URL_ERROR);
                }
                String adoResultString = JSONUtil.toJsonStr(execute.body());
                RequestSysVo<MemberCertificateOrderDo> adoResult = JSONUtil.toBean(adoResultString ,RequestSysVo.class);
                if (0 == adoResult.getCode()){
                    log.info("系统创建设备返回日志信息{}",adoResult.getData());
                    return JSONUtil.toBean( JSONUtil.toJsonStr( adoResult.getData()), MemberCertificateOrderDo.class);
                }else {
                    log.info("系统返回日志信息{}{}",MAIN_URL_EXCEPTION,adoResult.getMsg());
                    throw new RuntimeException(adoResult.getMsg());
                }
            }else {
                log.info("系统返回日志信息{}{}",MAIN_URL_EXCEPTION,requestSysVo.getMsg());
                throw new RuntimeException(requestSysVo.getMsg());
            }

        }catch (Exception e){
            log.info("系统返回日志信息{}",e.getMessage());
            throw exception(MAIN_URL_EXCEPTION,e.getMessage());
        }
    }

    @Override
    public String getSysType() {
        return SysFlagEnum.XIN_HANG.getType();
    }

    @Override
    public AppMemberCertificateOrderVo getById(MemberCertificateOrderDo  memberCertificateOrderDO) {
        SiteConfigurationVo config = siteConfigurationService.getConfig();
        SysLinkVo sysLinkVo = config.getSysLinkVos().stream().filter(t -> t.getMainUrl().equals(memberCertificateOrderDO.getMainUrl())).findFirst().orElse(null);
        String token = null;
        if (sysLinkVo != null) {
            token = sysLinkVo.getToken();
        }else {
            throw exception(MAIN_URL_ERROR);
        }
        String mainUrl = memberCertificateOrderDO.getMainUrl();
        long id = memberCertificateOrderDO.getSysId();
        try {
            //调用登录接口
            HttpResponse executeLogin = HttpUtil.createGet(mainUrl + Login_TO_A+"?token="+token).execute();
            if (!executeLogin.isOk()){
                throw exception(MAIN_URL_ERROR);
            }
            String s = JSONUtil.toJsonStr(executeLogin.body());
            RequestSysVo<AppAuthLoginRespVO> requestSysVo = JSONUtil.toBean(s, RequestSysVo.class);
            log.info("系统登录返回日志信息{}",s);
            if (0 == requestSysVo.getCode()){
                AppAuthLoginRespVO appAuthLoginRespVO = JSONUtil.toBean( JSONUtil.toJsonStr( requestSysVo.getData()), AppAuthLoginRespVO.class);
                HttpResponse execute = HttpUtil.createGet(mainUrl + GETBYID+"?id="+id).header("Authorization","Bearer "+appAuthLoginRespVO.getAccessToken()).execute();
                if (!execute.isOk()){
                    throw exception(MAIN_URL_ERROR);
                }
                String adoResultString = JSONUtil.toJsonStr(execute.body());
                RequestSysVo<AppMemberCertificateOrderVo> adoResult = JSONUtil.toBean(adoResultString ,RequestSysVo.class);
                if (0 == adoResult.getCode()){
                    log.info("系统创建设备返回日志信息{}",adoResult.getData());
                    return JSONUtil.toBean( JSONUtil.toJsonStr( adoResult.getData()), AppMemberCertificateOrderVo.class);
                }else {
                    log.info("系统返回日志信息{}{}",MAIN_URL_EXCEPTION,adoResult.getMsg());
                    throw new RuntimeException(adoResult.getMsg());
                }
            }else {
                log.info("系统返回日志信息{}{}",MAIN_URL_EXCEPTION,requestSysVo.getMsg());
                throw new RuntimeException(requestSysVo.getMsg());
            }

        }catch (Exception e){
            log.info("系统返回日志信息{}",e.getMessage());
            throw exception(MAIN_URL_EXCEPTION,e.getMessage());
        }
    }
}
